package com.yixun.qfbao.api.service.impl;

import com.yixun.common.page.Page;
import com.yixun.qfbao.api.service.*;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.dao.DepartmentDao;
import com.yixun.qfbao.model.*;
import com.yixun.qfbao.model.dto.*;
import com.yixun.qfbao.model.enums.CheckStatusEnum;
import com.yixun.qfbao.model.enums.DelFlagEnum;
import com.yixun.qfbao.model.enums.DimensionEnum;
import com.yixun.qfbao.service.PartnerInfoService;
import com.yixun.qfbao.util.DateStyle;
import com.yixun.qfbao.util.DateUtils;
import com.yixun.qfbao.util.exception.TServerException;
import com.yixun.qfbao.xf.mapper.CustomerPremisesMapper;
import com.yixun.qfbao.xf.model.dto.CustomerPremisesDto;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import com.yixun.qfbao.xf.service.CaseMemberService;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

/**
 * @author guifang.weng
 * @create 2017-11-27 15:20
 **/
@Service
public class DataCenterServiceImpl implements DataCenterService {

    private Logger logger = LoggerFactory.getLogger(DataCenterServiceImpl.class);

    @Autowired
    private CustomerPremisesMapper customerPremisesMapper;
    @Autowired
    private PremisesApiService premisesApiService;
    @Autowired
    private CompanyRelationService companyRelationService;
    @Autowired
    private CaseMemberService caseMemberService;
    @Autowired
    private DepartmentDao departmentDao;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private CustomerPremisesService customerPremisesService;
    @Autowired
    private PartnerInfoService partnerInfoService;
    @Autowired
    private DeptPermissionService deptPermissionService;
    @Autowired
    private PremisesPermissionService premisesPermissionService;
    @Autowired
    private EstateAdviserService estateAdviserService;

    @Override
    public GetAgentRankPageResDto getAgentRankPage(GetAgentRankPageReqDto reqDto) {
        GetAgentRankPageResDto resDto = new GetAgentRankPageResDto();
        AgentRankReportParam agentRankReportParam = new AgentRankReportParam();
        if (StringUtils.isNotBlank(reqDto.getBeginDate())) {
            agentRankReportParam.setBeginDate(DateUtils.StringToDate(reqDto.getBeginDate(), DateStyle.YYYY_MM_DD.getValue()));
        }
        if (StringUtils.isNotBlank(reqDto.getEndDate())) {
            Date temp = DateUtils.StringToDate(reqDto.getEndDate(), DateStyle.YYYY_MM_DD);
            temp = DateUtils.addDay(temp, 1);
            agentRankReportParam.setEndDate(temp);
        }
        agentRankReportParam.setCompanyId(Long.valueOf(reqDto.getMerchantId()));
        Integer pageNo = reqDto.getPageNo();
        Integer pageSize = reqDto.getPageSize();
        List<AgentRankReport> reportList = customerPremisesMapper.queryAgentRankReportByCompanyId(agentRankReportParam, (pageNo - 1) * pageSize, pageSize);
        int total = customerPremisesMapper.countAgentRankReportByCompanyId(agentRankReportParam);

        Page<AgentRankReport> page = new Page<>(total, reportList);
        page.setPageSize(pageSize);
        page.setPageNumber(pageNo);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        resDto.setPageModel(page);
        return resDto;
    }

    @Override
    public GetAgentRankExportResDto getAgentRankExport(GetAgentRankExportReqDto getAgentRankExportReqDto) {
        GetAgentRankExportResDto resDto = new GetAgentRankExportResDto();
        String op = getAgentRankExportReqDto.getOp();
        Integer pageNo = getAgentRankExportReqDto.getPageNo();
        Integer pageSize = getAgentRankExportReqDto.getPageNo();
        if("all".equals(op)){
            //导出全部数据，暂时设置成100000条
            pageNo = 1;
            pageSize = 100000;
        }
        String beginDate = getAgentRankExportReqDto.getBeginDate();
        String endDate = getAgentRankExportReqDto.getEndDate();
        AgentRankReportParam agentRankReportParam=new  AgentRankReportParam();
        if(StringUtils.isNotBlank(beginDate)){
            agentRankReportParam.setBeginDate(DateUtils.StringToDate(beginDate, DateStyle.YYYY_MM_DD));
        }
        if(StringUtils.isNotBlank(endDate)){
            Date temp=DateUtils.StringToDate(endDate, DateStyle.YYYY_MM_DD);
            temp= DateUtils.addDay(temp, 1);
            agentRankReportParam.setEndDate(temp);
        }
        agentRankReportParam.setCompanyId(Long.valueOf(getAgentRankExportReqDto.getMerchantId()));
        List<AgentRankReport> reportList = customerPremisesMapper.queryAgentRankReportByCompanyId(agentRankReportParam, (pageNo - 1) * pageNo, pageSize);
        int count = customerPremisesMapper.countAgentRankReportByCompanyId(agentRankReportParam);
        Page<AgentRankReport> page = new Page<>();
        page.setRows(reportList);
        page.setPageInfo(count, (pageNo - 1) * pageNo, pageSize);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        resDto.setAgentRankReportPage(page);
        return resDto;
    }

    @Override
    public GetCustomerConversionPageResDto getCustomerConversionPage(GetCustomerConversionPageReqDto reqDto) {
        GetCustomerConversionPageResDto resDto = new GetCustomerConversionPageResDto();

        CustomerConversionReportParam param = new CustomerConversionReportParam();
        if (StringUtils.isNotBlank(reqDto.getBeginDate())) {
            param.setBeginDate(DateUtils.StringToDate(reqDto.getBeginDate(), DateStyle.YYYY_MM_DD));
        }
        if (StringUtils.isNotBlank(reqDto.getEndDate())) {
            Date temp = DateUtils.StringToDate(reqDto.getEndDate(), DateStyle.YYYY_MM_DD);
            temp = DateUtils.addDay(temp, 1);
            param.setEndDate(temp);
        }
        if (StringUtils.isNotBlank(reqDto.getPremisesId())) {
            param.setPremisesId(Long.parseLong(reqDto.getPremisesId()));
        }
        List<String> saleStatusList = buildSaleStatus(reqDto.getSaleStatus());
        param.setSaleStatuses(saleStatusList);
        param.setValidateData(reqDto.isValidateData());
        // 渠道经理所在机构的所有经纪人
        List<List<Long>> staffIds = getStaffIdsByPrincipal(Long.valueOf(reqDto.getUserId()));
        if(CollectionUtils.isNotEmpty(staffIds)){
            param.setStaffIds(staffIds);
        }
        // 楼盘权限
        List<Long> premisesIds = premisesPermissionService.getPartnerPremisesPermission(Long.valueOf(reqDto.getUserId()));
        if(CollectionUtils.isEmpty(premisesIds)){
            param.setPremisesIds(Arrays.asList(-1L));
        }else{
            param.setPremisesIds(premisesIds);
        }
        // 机构权限
        List<Long> agencyDeptIds = deptPermissionService.getPartnerDeptPermission(Long.valueOf(reqDto.getUserId()));
        param.setAgencyDeptIds(agencyDeptIds);
        Integer pageNo = reqDto.getPageNo();
        Integer pageSize = reqDto.getPageSize();
        List<CustomerConversionReport> rows = customerPremisesMapper.queryCustomerConversionReport(param, (pageNo - 1) * pageSize, pageSize);
        int count = customerPremisesMapper.countCustomerConversionReport(param);

        Page<CustomerConversionReport> page = new Page<>(count, rows);
        page.setPageSize(pageSize);
        page.setPageNumber(pageNo);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        resDto.setPageModel(page);
        return resDto;

    }

    @Override
    public GetCustomerConversionExportResDto getCustomerConversionExport(GetCustomerConversionExportReqDto reqDto) {
        GetCustomerConversionExportResDto resDto = new GetCustomerConversionExportResDto();

        String op = reqDto.getOp();
        Integer pageNo = reqDto.getPageNo();
        Integer pageSize = reqDto.getPageSize();
        if ("all".equals(op)) {
            //导出全部，暂时设置100000
            pageNo = 1;
            pageSize = 100000;
        }
        CustomerConversionReportParam param = new CustomerConversionReportParam();
        String beginDate = reqDto.getBeginDate();
        if (StringUtils.isNotBlank(beginDate)) {
            param.setBeginDate(DateUtils.StringToDate(beginDate, DateStyle.YYYY_MM_DD));
        }
        String endDate = reqDto.getEndDate();
        if (StringUtils.isNotBlank(endDate)) {
            Date temp = DateUtils.StringToDate(endDate, DateStyle.YYYY_MM_DD);
            temp = DateUtils.addDay(temp, 1);
            param.setEndDate(temp);
        }
        String premisesId = reqDto.getPremisesId();
        if (StringUtils.isNotBlank(premisesId)) {
            param.setPremisesId(Long.valueOf(premisesId));
        } else {
            //获取楼盘ID集合
            PartnerInfo partnerInfo = new PartnerInfo();
            partnerInfo.setId(Long.valueOf(reqDto.getUserId()));
            partnerInfo.setHigherid(reqDto.getMerchantId());
            partnerInfo.setAccountType(reqDto.getAccountType());
            List<Long> premisesIds = premisesApiService.getPremisesIdsList(partnerInfo);
            if (premisesIds != null && premisesIds.size() > 0) {
                param.setPremisesIds(premisesIds);
            }
        }

        // 渠道经理所在机构的所有经纪人
        List<List<Long>> staffIds = getStaffIdsByPrincipal(Long.valueOf(reqDto.getUserId()));
        if(CollectionUtils.isNotEmpty(staffIds)){
            param.setStaffIds(staffIds);
        }

        List<Long> staffPremisesIds = customerPremisesMapper.selectPremisesIdsByStaffIds(staffIds);
        if(CollectionUtils.isNotEmpty(staffPremisesIds)){
            staffPremisesIds.addAll(param.getPremisesIds());
            param.setStaffPremisesIds(staffPremisesIds);
        }

        List<String> saleStatusList = buildSaleStatus(reqDto.getSaleStatus());
        param.setSaleStatuses(saleStatusList);
        param.setValidateData(reqDto.isValidateData());

        List<Long> agencyDeptIds = deptPermissionService.getPartnerDeptPermission(Long.valueOf(reqDto.getUserId()));
        param.setAgencyDeptIds(agencyDeptIds);

        List<CustomerConversionReport> rows = customerPremisesMapper.queryCustomerConversionReport(param, (pageNo - 1) * pageSize, pageSize);
        int count = customerPremisesMapper.countCustomerConversionReport(param);
        Page<CustomerConversionReport> page = new Page<>(count,rows);
        page.setPageSize(pageSize);
        page.setPageNumber(pageNo);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        resDto.setCustomerConversionReportPage(page);
        return resDto;
    }

    @Override
    public GetEffectPageResDto getEffectPage(GetEffectPageReqDto reqDto) {
        GetEffectPageResDto resDto = new GetEffectPageResDto();
        ChannelEffectReportParam param = new ChannelEffectReportParam();
        Integer pageNo = reqDto.getPageNo();
        Integer pageSize = reqDto.getPageSize();
        if (StringUtils.isNotBlank(reqDto.getBeginDate())) {
            param.setBeginDate(DateUtils.StringToDate(reqDto.getBeginDate(), DateStyle.YYYY_MM_DD));
        }
        if (StringUtils.isNotBlank(reqDto.getEndDate())) {
            Date temp = DateUtils.StringToDate(reqDto.getEndDate(), DateStyle.YYYY_MM_DD);
            temp = DateUtils.addDay(temp, 1);
            param.setEndDate(temp);
        }
        //合作经济公司
        CompanyRelationDto crDto = new CompanyRelationDto();
        crDto.setDevCompany(reqDto.getMerchantId());
        List<CompanyRelation> crList = companyRelationService.selectListByDto(crDto);
        if (null != crList && crList.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (int ii = 0; ii < crList.size(); ii++) {
                CompanyRelation cr = crList.get(ii);
                sb.append(cr.getAgentCompany());
                if (ii != (crList.size() - 1)) {
                    sb.append(",");
                }
            }
            if (StringUtils.isNotEmpty(sb.toString())) {
                param.setStaffCompanyIds(sb.toString());
            } else {
                //无合作机构时,不展示信息
                param.setStaffCompanyIds("1=2");
            }
        }
        if (StringUtils.isNotBlank(reqDto.getPremisesId())) {
            param.setPremisesId(Long.valueOf(reqDto.getPremisesId()));
        }

        param.setDevCompanyId(reqDto.getMerchantId());
        param.setCompanyName(reqDto.getCompanyName());
        param.setHasVisit(reqDto.getHasVisit());

        List<String> saleStatusList = buildSaleStatus(reqDto.getSaleStatus());
        param.setSaleStatuses(saleStatusList);
        param.setValidateData(reqDto.isValidateData());

        // 楼盘权限
        List<Long> premisesIds = premisesPermissionService.getPartnerPremisesPermission(Long.valueOf(reqDto.getUserId()));
        if(CollectionUtils.isEmpty(premisesIds)){
            param.setPremisesIds(Arrays.asList(-1L));
        }else{
            param.setPremisesIds(premisesIds);
        }

        List<Long> agencyDeptIds = deptPermissionService.getPartnerDeptPermission(Long.valueOf(reqDto.getUserId()));
        param.setAgencyDeptIds(agencyDeptIds);

        int count = customerPremisesMapper.countAllChannelEffectReport(param);
        List<ChannelEffectReport> rows = customerPremisesMapper.queryAllChannelEffectReport(param, (pageNo - 1) * pageSize, pageSize);

        String companyIds = "";
        for(int ii=0; ii<rows.size(); ii++){
            ChannelEffectReport report = rows.get(ii);
            companyIds += String.valueOf(report.getId());
            if(ii != rows.size() -1 ){
                companyIds += ",";
            }
        }
        DepartmentDto departmentDto = new DepartmentDto();
        departmentDto.setMerchantIds(companyIds);
        List<DepartmentDto> departmentDtoList = departmentDao.selectPrincipalNameByCompany(departmentDto);
        Map<Long, String> departmentMap = departmentDtoList.stream()
                .collect(Collectors.toMap(DepartmentDto::getMerchantId, DepartmentDto::getPrincipalName, (oldData, newData) -> newData));
        rows.forEach(item -> {
            String principalName = departmentMap.get(item.getId());
            item.setPrincipalName(principalName);
        });
        Page<ChannelEffectReport> page = new Page<>(count, rows);
        page.setPageSize(pageSize);
        page.setPageNumber(pageNo);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        resDto.setPageModel(page);
        return resDto;
    }

    @Override
    public GetEffectExportResDto getEffectExport(GetEffectExportReqDto reqDto) {
        GetEffectExportResDto resDto = new GetEffectExportResDto();
        String op = reqDto.getOp();
        Integer pageSize = reqDto.getPageSize();
        Integer pageNo = reqDto.getPageNo();
        if ("all".equals(op)) {
            //说明导出全部数据，暂时设置100000条
            pageNo = 1;
            pageSize = 100000;
        }
        ChannelEffectReportParam param = new ChannelEffectReportParam();
        String beginDate = reqDto.getBeginDate();
        if (StringUtils.isNotBlank(beginDate)) {
            param.setBeginDate(DateUtils.StringToDate(beginDate, DateStyle.YYYY_MM_DD));
        }
        String endDate = reqDto.getEndDate();
        if (StringUtils.isNotBlank(endDate)) {
            Date temp = DateUtils.StringToDate(endDate, DateStyle.YYYY_MM_DD);
            temp = DateUtils.addDay(temp, 1);
            param.setEndDate(temp);
        }

        //合作经济公司
        Long devCompany = reqDto.getMerchantId();
        CompanyRelationDto crDto = new CompanyRelationDto();
        crDto.setDevCompany(devCompany);
        List<CompanyRelation> crList = companyRelationService.selectListByDto(crDto);
        if (null != crList && crList.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (int ii = 0; ii < crList.size(); ii++) {
                CompanyRelation cr = crList.get(ii);
                sb.append(cr.getAgentCompany());
                if (ii != (crList.size() - 1)) {
                    sb.append(",");
                }
            }
            if (StringUtils.isNotEmpty(sb.toString())) {
                param.setStaffCompanyIds(sb.toString());
            } else {
                //无合作机构时,不展示信息
                param.setStaffCompanyIds("1=2");
            }
        }
        String premisesId = reqDto.getPremisesId();
        if (StringUtils.isNotBlank(premisesId)) {
            param.setPremisesId(Long.valueOf(premisesId));
        }
        param.setDevCompanyId(reqDto.getMerchantId());

        List<String> saleStatusList = buildSaleStatus(reqDto.getSaleStatus());
        param.setSaleStatuses(saleStatusList);
        param.setValidateData(reqDto.isValidateData());

        // 楼盘权限
        List<Long> premisesIds = premisesPermissionService.getPartnerPremisesPermission(Long.valueOf(reqDto.getUserId()));
        if(CollectionUtils.isEmpty(premisesIds)){
            param.setPremisesIds(Arrays.asList(-1L));
        }else{
            param.setPremisesIds(premisesIds);
        }

        List<Long> agencyDeptIds = deptPermissionService.getPartnerDeptPermission(Long.valueOf(reqDto.getUserId()));
        param.setAgencyDeptIds(agencyDeptIds);

        List<ChannelEffectReport> rows = customerPremisesMapper.queryAllChannelEffectReport(param,(pageNo - 1) * pageSize, pageSize);
        int count = customerPremisesMapper.countAllChannelEffectReport(param);
        Page<ChannelEffectReport> page = new Page<>(count, rows);
        page.setPageInfo(count, (pageNo - 1) * pageSize, pageSize);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        resDto.setChannelEffectReportPage(page);
        return resDto;
    }

    /**
     * 获取门店业绩表
     * @param reqDto
     * @return
     */
    @Override
    public GetStoreReportPageResDto getStoreReport(GetStoreReportPageReqDto reqDto){GetStoreReportPageResDto resDto = new GetStoreReportPageResDto();
        ChannelEffectReportParam channelEffectReportParam = new ChannelEffectReportParam();
        List<Long> deptIds = new ArrayList<>();
        Integer pageSize = reqDto.getPageSize();
        Integer pageNo = reqDto.getPageNo();
        //模糊查询门店
        if(StringUtils.isNotEmpty(reqDto.getStoreName())){
            DepartmentDto departmentDto = new DepartmentDto();
            departmentDto.setDepartmentName(reqDto.getStoreName());
            departmentDto.setMerchantId(reqDto.getOrgId());
            List<Department> departmentList = departmentDao.getListByName(departmentDto);
            List<Long> departmentIds = departmentList.stream().map(Department::getId).collect(Collectors.toList());
            channelEffectReportParam.setStoreIds(departmentIds);
        }
        //获取一级合作机构的部门id
        DepartmentDto staffDepartmentDto = new DepartmentDto();
        staffDepartmentDto.setParentId(0L);
        staffDepartmentDto.setMerchantId(reqDto.getOrgId());
        Department staffDepartment = departmentDao.selectByDto(staffDepartmentDto);
        if(staffDepartment == null){
            //如果没有合作机构 返回空数据
            Page<ChannelEffectReport> page = new Page<>(0, null);
            resDto.setResult(ResultEnum.SUCCESS.getNo());
            resDto.setPageModel(page);
            return resDto;
        }
        //合作机构的部门id
        channelEffectReportParam.setParentId(staffDepartment.getId());
        deptIds.add(staffDepartment.getId());
        //获取门店的部门id
        DepartmentDto departmentDto = new DepartmentDto();
        departmentDto.setParentId(staffDepartment.getId());
        List<Department> departmentList = departmentDao.selectListByDto(departmentDto);
        for(Department d : departmentList){
            deptIds.add(d.getId());
        }
        channelEffectReportParam.setDeptIds(deptIds);
        //开发商id
        channelEffectReportParam.setDevCompanyId(reqDto.getDevCompanyId());
        //楼盘id
        channelEffectReportParam.setPremisesId(reqDto.getPremisesId());
        //合作机构id
        if(reqDto.getOrgId() != null){
            channelEffectReportParam.setStaffCompanyId(reqDto.getOrgId());
        }
        List<Long> agencyDeptIds = deptPermissionService.getPartnerDeptPermission(Long.valueOf(reqDto.getUserId()));
        channelEffectReportParam.setAgencyDeptIds(agencyDeptIds);
        //开始时间
        channelEffectReportParam.setBeginDate(reqDto.getBeginDate());
        //结束时间
        channelEffectReportParam.setEndDate(reqDto.getEndDate());
        int count = customerPremisesMapper.queryStoreReportCount(channelEffectReportParam);
        List<ChannelEffectReport> list = customerPremisesMapper.queryStoreReport(channelEffectReportParam,(pageNo - 1) * pageSize, pageSize);
        Page<ChannelEffectReport> page = new Page<>(count, list);
        page.setPageSize(pageSize);
        page.setPageNumber(pageNo);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        resDto.setPageModel(page);
        return resDto;

    }

    /**
     * 获取组别业绩报表
     * @param reqDto
     * @return
     */
    @Override
    public GetGroupReportPageResDto getGroupReportPage(GetGroupReportPageReqDto reqDto){
        GetGroupReportPageResDto resDto = new GetGroupReportPageResDto();
        ChannelEffectReportParam channelEffectReportParam = new ChannelEffectReportParam();
        Integer pageSize = reqDto.getPageSize();
        Integer pageNo = reqDto.getPageNo();
        //查询组别id
        DepartmentDto departmentDto = new DepartmentDto();
        if(StringUtils.isNotEmpty(reqDto.getStoreName())){
            departmentDto.setDepartmentName(reqDto.getStoreName());
        }
        //门店id
        departmentDto.setParentId(reqDto.getStoreId());
        //商户id
        departmentDto.setMerchantId(reqDto.getOrgId());
        List<Department> departmentList = departmentDao.getListByName(departmentDto);
        //没有组别返回空数据
        if(departmentList == null || departmentList.size() == 0){
            Page<ChannelEffectReport> page = new Page<>(0, null);
            page.setPageSize(pageSize);
            page.setPageNumber(pageNo);
            resDto.setResult(ResultEnum.SUCCESS.getNo());
            resDto.setPageModel(page);
            return resDto;
        }
        List<Long> departmentIds = departmentList.stream().map(Department::getId).collect(Collectors.toList());
        channelEffectReportParam.setGroupIds(departmentIds);
        channelEffectReportParam.setBeginDate(reqDto.getBeginDate());
        channelEffectReportParam.setEndDate(reqDto.getEndDate());
        channelEffectReportParam.setStoreName(reqDto.getStoreName());
        channelEffectReportParam.setPremisesId(reqDto.getPremisesId());

        List<String> saleStatusList = buildSaleStatus(reqDto.getSaleStatus());
        channelEffectReportParam.setSaleStatuses(saleStatusList);
        channelEffectReportParam.setValidateData(reqDto.isValidateData());

        List<Long> agencyDeptIds = deptPermissionService.getPartnerDeptPermission(Long.valueOf(reqDto.getUserId()));
        channelEffectReportParam.setAgencyDeptIds(agencyDeptIds);

        int count = customerPremisesMapper.selectGroupReportCount(channelEffectReportParam);
        List<ChannelEffectReport> list = customerPremisesMapper.selectGroupReport(channelEffectReportParam,(pageNo - 1) * pageSize, pageSize);

        Page<ChannelEffectReport> page = new Page<>(count, list);
        page.setPageSize(pageSize);
        page.setPageNumber(pageNo);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        resDto.setPageModel(page);
        return resDto;
    }

    /**
     * 获取经济人业绩表
     * @param reqDto
     * @return
     */
    public GetAgentReportPageResDto getAgentReport(GetAgentReportPageReqDto reqDto){
        List<Long> deptIds = new ArrayList<>();
        GetAgentReportPageResDto resDto = new GetAgentReportPageResDto();
        String domain = reqDto.getDomain();
        String companyUuid=reqDto.getCompanyUuid();
        if(!reqDto.isUnderStore() && !reqDto.isUnderOrg() && !reqDto.isUnderGroup()){
            resDto.setPageModel(new Page(0,null));
            resDto.getPageModel().setTotal(0);
            return resDto;
        }
        // 根据域名或者公司uuid查询开发商
        CompanyDto cDto = new CompanyDto();
        cDto.setDomain(domain);
        cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
        cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        cDto.setCompanyUuid(companyUuid);
        Company company = companyService.selectByDto(cDto);

        if (null == company) {
            //此处为商户不存在
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setResultMsg("未获取到开发商信息!");
            return resDto;
        }
        if(reqDto.isUnderOrg()){
            DepartmentDto departmentDto = new DepartmentDto();
            departmentDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
            departmentDto.setMerchantId(reqDto.getOrgId());

            departmentDto.setParentId(0L);
            List<Department> merchants = departmentDao.getListByDev(departmentDto,company.getId());
            if(merchants != null && merchants.size() > 0)
                deptIds.add(merchants.get(0).getId());
        }
        if(reqDto.isUnderStore()){
            if(reqDto.getStoreId() == null && reqDto.getGroupId() == null){
                addDeptByOrg(reqDto.getOrgId(),deptIds,company.getId());
            }
            deptIds.add(reqDto.getStoreId());
        }

        if(reqDto.isUnderGroup()){
            if(reqDto.getStoreId() != null && reqDto.getGroupId() == null ){
                addDeptByStore(reqDto.getStoreId(),deptIds);
            }
            deptIds.add(reqDto.getGroupId());
        }

        //如果部门为空则返回空数据
        if(deptIds == null || deptIds.size() == 0){
           resDto.setPageModel(new Page<ChannelEffectReport>(0,null));
           resDto.setResult(ResultEnum.SUCCESS.getNo());
           resDto.getPageModel().setTotal(0);
           return resDto;
        }


        ChannelEffectReportParam channelEffectReportParam = new ChannelEffectReportParam();
        channelEffectReportParam.setDeptIds(deptIds);
        channelEffectReportParam.setPremisesId(reqDto.getPremisesId());
        channelEffectReportParam.setBeginDate(reqDto.getBeginDate());
        if (reqDto.getEndDate() != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String endDateStr = sdf.format(reqDto.getEndDate()).split(" ")[0];
            endDateStr += " 23:59:59";
            try {
                channelEffectReportParam.setEndDate(sdf.parse(endDateStr));
            } catch (ParseException e) {
                logger.error("时间转换异常：{}", e);
            }
        }

        List<String> saleStatusList = buildSaleStatus(reqDto.getSaleStatus());
        channelEffectReportParam.setSaleStatuses(saleStatusList);
        channelEffectReportParam.setValidateData(reqDto.isValidateData());

        Integer pageSize = reqDto.getPageSize();
        Integer pageNo = reqDto.getPageNo();

        List<Long> agenctDeptIds = deptPermissionService.getPartnerDeptPermission(Long.valueOf(reqDto.getUserId()));
        channelEffectReportParam.setAgencyDeptIds(agenctDeptIds);

        int count = customerPremisesMapper.selectAgentReportCount(channelEffectReportParam);
        List<ChannelEffectReport> list = customerPremisesMapper.selectAgentReport(channelEffectReportParam,(pageNo - 1) * pageSize, pageSize);


        Page<ChannelEffectReport> page = new Page<>(count, list);
        page.setPageSize(pageSize);
        page.setPageNumber(pageNo);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        resDto.setPageModel(page);
        return resDto;

    }

    /**
     * 当groupId,storeId为空 时获取合作机构下的所有部门
     * @param merchantId
     * @param deptIds
     */
    @Override
    public void addDeptByOrg(Long merchantId,List<Long> deptIds,Long devId){
        DepartmentDto departmentDto = new DepartmentDto();
        departmentDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        departmentDto.setMerchantId(merchantId);

        departmentDto.setParentId(0L);
        List<Department> parentDepts = departmentDao.getListByDev(departmentDto,devId);
        for(Department d : parentDepts){
            deptIds.add(d.getId());
        }
        if(null == parentDepts || parentDepts.size() == 0){
            return;
        }
        //stores
        List<Department> storeDepts = departmentDao.getListByParent(parentDepts);
        for(Department subD : storeDepts){
            deptIds.add(subD.getId());
        }
        if(null == storeDepts || storeDepts.size() == 0){
            return;
        }
        //group
        List<Department> groupDepts = departmentDao.getListByParent(storeDepts);
        for(Department groupD : groupDepts){
            deptIds.add(groupD.getId());
        }
    }

    /**
     * 当storeId不为空，groupId为空时获取该门店下的所有部门
     * @param parentId
     * @param deptIds
     */
    @Override
    public void addDeptByStore(Long parentId,List<Long> deptIds){
        DepartmentDto departmentDto = new DepartmentDto();
        departmentDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        departmentDto.setParentId(parentId);
        List<Department> depts = departmentDao.selectListByDto(departmentDto);
        for(Department d : depts){
            deptIds.add(d.getId());
        }
    }

    /**
     * 组装销售状态查询字段
     *
     * @param saleStatus
     * @return
     */
    private List<String> buildSaleStatus(String saleStatus){
        List<String> saleStatusList = new ArrayList<>();
        if(StringUtils.isNotBlank(saleStatus)){
            String[] saleStatusArr = saleStatus.split(",");
            for(String status: saleStatusArr){
                saleStatusList.add(status);
            }
        }
        return saleStatusList;
    }


    @Override
    public HouseSalePerformancePageListResDto houseSalePerformancePageList(HouseSalePerformancePageListReqDto reqDto) {

        if (StringUtils.isBlank(reqDto.getCompanyUuid())) {
            throw new TServerException("公司信息不能为空！");
        }
        if (StringUtils.isBlank(reqDto.getDimension())) {
            throw new TServerException("日期维度不能为空！");
        }
        if (StringUtils.isBlank(reqDto.getBeginTime())) {
            throw new TServerException("开始时间不能为空！");
        }
        if (StringUtils.isBlank(reqDto.getEndTime()) && reqDto.getDimension().equals(DimensionEnum.WEEK.getCode())) {
            throw new TServerException("结束时间不能为空");
        }
        if (StringUtils.isBlank(reqDto.getUserId())) {
            throw new TServerException("人员ID不能为空！");
        }

        HouseSalePerformancePageListResDto resDto = new HouseSalePerformancePageListResDto();
        Map<String, Object> param = new HashMap<>();
        param.put("companyUuid", reqDto.getCompanyUuid());
        param.put("dimension", reqDto.getDimension());
        DateStyle dateStyle = reqDto.getDimension().equals(DimensionEnum.MONTH.getCode()) ? DateStyle.YYYY_MM : DateStyle.YYYY_MM_DD;
        Date beginTime = DateUtils.StringToDate(reqDto.getBeginTime(), dateStyle);
        param.put("beginTime", beginTime);
        Date endTime = null;
        if (StringUtils.isNotBlank(reqDto.getEndTime())) {
            endTime = DateUtils.StringToDate(reqDto.getEndTime(), DateStyle.YYYY_MM_DD);
            endTime = DateUtils.addDay(endTime, 1);
        }else {
        	if(reqDto.getDimension().equals(DimensionEnum.DAY.getCode())){
            	endTime = DateUtils.addDay(beginTime, 1);
        	} else if(reqDto.getDimension().equals(DimensionEnum.WEEK.getCode())) {
        		endTime = DateUtils.addDay(beginTime, 7);
        	} else if(reqDto.getDimension().equals(DimensionEnum.MONTH.getCode())) {
        		endTime = DateUtils.addMonth(beginTime, 1);
        	}
        }
        	
        param.put("endTime", endTime);

        // 添加权限相关数据作为查询条件
        List<Long> premisesIds = premisesPermissionService.getPartnerPremisesPermission(Long.parseLong(reqDto.getUserId()));
        if(CollectionUtils.isEmpty(premisesIds)){
        	param.put("authorityPremisesIds", Arrays.asList(-1L));
        }else{
        	param.put("authorityPremisesIds", premisesIds);
        }
        // 机构权限.直接以机构来查询.
        List<Long> deptPermissionList = deptPermissionService.getPartnerDeptPermission(Long.parseLong(reqDto.getUserId()));
        param.put("agencyDeptIds", deptPermissionList);
        // 置业顾问数据
        List<EstateAdviser> estateAdviserList = estateAdviserService.selectListByPartner(Long.parseLong(reqDto.getUserId()));
        if (CollectionUtils.isNotEmpty(estateAdviserList)) {
            List<String> adviserUuids = estateAdviserList.stream().map(EstateAdviser::getAdviserUuid).collect(Collectors.toList());
            param.put("adviserUuids", adviserUuids);
        }
        param.put("companyId", reqDto.getHigherId());
        Integer pageNo = reqDto.getPageNo();
        Integer pageSize = reqDto.getPageSize();
        List<HouseSalePerformanceDto> list = customerPremisesMapper.houseSalePerformancePageList(param, (pageNo - 1) * pageSize, pageSize);
//        int count = customerPremisesMapper.houseSalePerformancePageCount(param);
        //不再查询总数量。增加效率
        int count = 0;
        DecimalFormat df = new DecimalFormat("#,###");
        BigDecimal divisor = new BigDecimal("10000");
        BigDecimal totalAmount = new BigDecimal("0");
        if(null != list && list.size() > 0) {
            for (HouseSalePerformanceDto houseSalePerformanceDto : list) {
                BigDecimal dealAmount = new BigDecimal(houseSalePerformanceDto.getDealAmount());
                houseSalePerformanceDto.setDealAmount(df.format(Math.round(dealAmount.divide(divisor).doubleValue())));
            }
            if(reqDto.getPageSize() > 5) {
                CustomerPremisesDto customerPremisesDto = new CustomerPremisesDto();
                if(CollectionUtils.isEmpty(premisesIds)){
                	customerPremisesDto.setAuthorityPremisesIds(Arrays.asList(-1L));
                }else{
                	customerPremisesDto.setAuthorityPremisesIds(premisesIds);
                }
        		 customerPremisesDto.setAgencyDeptIds(deptPermissionList);
                // 置业顾问数据
                if (CollectionUtils.isNotEmpty(estateAdviserList)) {
                    List<String> adviserUuids = estateAdviserList.stream().map(EstateAdviser::getAdviserUuid).collect(Collectors.toList());
                    customerPremisesDto.setAdviserUuids(adviserUuids);
                }
                customerPremisesDto.setCompanyId(reqDto.getHigherId());
                customerPremisesDto.setCreateTimeBefore(beginTime);
                customerPremisesDto.setCreateTimeAfter(endTime);
                customerPremisesDto.setDimension(reqDto.getDimension());
                Future<String> totalAmountFuture = customerPremisesService.querySignAmountCount(customerPremisesDto);
                try {
					String totalAmountString = totalAmountFuture.get();
					if(StringUtils.isNotBlank(totalAmountString) && !"null".equals(totalAmountString)) {
						totalAmount = new BigDecimal(totalAmountString);
					}
				} catch (InterruptedException | ExecutionException e) {
					logger.error(e.getMessage(), e);
				}
            }
        }

        Page<HouseSalePerformanceDto> page = new Page<>(count, list);
        page.setPageSize(pageSize);
        page.setPageNumber(pageNo);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        resDto.setPage(page);
        if(totalAmount == null) {
        	resDto.setTotalAmount("0");
        }else {
        	resDto.setTotalAmount(df.format(Math.round(totalAmount.divide(divisor).doubleValue())));
        }
        return resDto;
    }

    @Override
    public OrganSalePerformancePageListResDto organSalePerformancePageList(OrganSalePerformancePageListReqDto reqDto) {
        if (StringUtils.isBlank(reqDto.getCompanyUuid())) {
            throw new TServerException("公司信息不能为空！");
        }
        if (StringUtils.isBlank(reqDto.getDimension())) {
            throw new TServerException("日期维度不能为空！");
        }
        if (StringUtils.isBlank(reqDto.getBeginTime())) {
            throw new TServerException("开始时间不能为空！");
        }
        if (StringUtils.isBlank(reqDto.getEndTime()) && reqDto.getDimension().equals(DimensionEnum.WEEK.getCode())) {
            throw new TServerException("结束时间不能为空");
        }
        if (StringUtils.isBlank(reqDto.getUserId())) {
            throw new TServerException("人员ID不能为空！");
        }

        OrganSalePerformancePageListResDto resDto = new OrganSalePerformancePageListResDto();
        Map<String, Object> param = new HashMap<>();
        param.put("companyUuid", reqDto.getCompanyUuid());
        param.put("dimension", reqDto.getDimension());
        DateStyle dateStyle = reqDto.getDimension().equals(DimensionEnum.MONTH.getCode()) ? DateStyle.YYYY_MM : DateStyle.YYYY_MM_DD;
        Date beginTime = DateUtils.StringToDate(reqDto.getBeginTime(), dateStyle);
        param.put("beginTime", beginTime);
        Date endTime = null;
        if (StringUtils.isNotBlank(reqDto.getEndTime())) {
            endTime = DateUtils.StringToDate(reqDto.getEndTime(), DateStyle.YYYY_MM_DD);
            endTime = DateUtils.addDay(endTime, 1);
        } else {
        	if(reqDto.getDimension().equals(DimensionEnum.DAY.getCode())){
            	endTime = DateUtils.addDay(beginTime, 1);
        	} else if(reqDto.getDimension().equals(DimensionEnum.WEEK.getCode())) {
        		endTime = DateUtils.addDay(beginTime, 7);
        	} else if(reqDto.getDimension().equals(DimensionEnum.MONTH.getCode())) {
        		endTime = DateUtils.addMonth(beginTime, 1);
        	}
        }
        param.put("endTime", endTime);

        param.put("devCompanyId",reqDto.getHigherId());
        
        // 添加权限相关数据作为查询条件
        List<Long> premisesIds = premisesPermissionService.getPartnerPremisesPermission(Long.parseLong(reqDto.getUserId()));
        if(CollectionUtils.isEmpty(premisesIds)){
        	param.put("authorityPremisesIds", Arrays.asList(-1L));
        }else{
        	param.put("authorityPremisesIds", premisesIds);
        }
        // 机构权限.直接以机构来查询.
        List<Long> deptPermissionList = deptPermissionService.getPartnerDeptPermission(Long.parseLong(reqDto.getUserId()));
        param.put("agencyDeptIds", deptPermissionList);
        // 置业顾问数据
        List<EstateAdviser> estateAdviserList = estateAdviserService.selectListByPartner(Long.parseLong(reqDto.getUserId()));
        if (CollectionUtils.isNotEmpty(estateAdviserList)) {
            List<String> adviserUuids = estateAdviserList.stream().map(EstateAdviser::getAdviserUuid).collect(Collectors.toList());
            param.put("adviserUuids", adviserUuids);
        }
//        param.put("companyId", reqDto.getHigherId());
        

        Integer pageNo = reqDto.getPageNo();
        Integer pageSize = reqDto.getPageSize();
        List<OrganSalePerformanceDto> list = customerPremisesMapper.organSalePerformancePageList(param, (pageNo - 1) * pageSize, pageSize);
//        int count = customerPremisesMapper.organSalePerformancePageCount(param);
        // 不再查询总数量，增加效率
        int count = 0;

        DecimalFormat df = new DecimalFormat("#,###");
        BigDecimal divisor = new BigDecimal("10000");
        BigDecimal totalAmount = new BigDecimal("0");
        if(null != list && list.size() > 0) {
            for (OrganSalePerformanceDto organSalePerformanceDto : list) {
                BigDecimal dealAmount = new BigDecimal(organSalePerformanceDto.getDealAmount());
                organSalePerformanceDto.setDealAmount(df.format(Math.round(dealAmount.divide(divisor).doubleValue())));
            }
            if(reqDto.getPageSize() > 5) {
                CustomerPremisesDto customerPremisesDto = new CustomerPremisesDto();
                if(CollectionUtils.isEmpty(premisesIds)){
                	customerPremisesDto.setAuthorityPremisesIds(Arrays.asList(-1L));
                }else{
                	customerPremisesDto.setAuthorityPremisesIds(premisesIds);
                }
        		 customerPremisesDto.setAgencyDeptIds(deptPermissionList);
                // 置业顾问数据
                if (CollectionUtils.isNotEmpty(estateAdviserList)) {
                    List<String> adviserUuids = estateAdviserList.stream().map(EstateAdviser::getAdviserUuid).collect(Collectors.toList());
                    customerPremisesDto.setAdviserUuids(adviserUuids);
                }
                customerPremisesDto.setCompanyId(reqDto.getHigherId());
                customerPremisesDto.setCreateTimeBefore(beginTime);
                customerPremisesDto.setCreateTimeAfter(endTime);
                customerPremisesDto.setDimension(reqDto.getDimension());
                Future<String> totalAmountFuture = customerPremisesService.querySignAmountCount(customerPremisesDto);
                try {
					String totalAmountString = totalAmountFuture.get();
					if(StringUtils.isNotBlank(totalAmountString) && !"null".equals(totalAmountString)) {
						totalAmount = new BigDecimal(totalAmountString);
					}
				} catch (InterruptedException | ExecutionException e) {
					logger.error(e.getMessage(), e);
				}
            }
        }

        Page<OrganSalePerformanceDto> page = new Page<>(count, list);
        page.setPageSize(pageSize);
        page.setPageNumber(pageNo);
        resDto.setResult(ResultEnum.SUCCESS.getNo());
        resDto.setPage(page);
        resDto.setTotalAmount(df.format(Math.round(totalAmount.divide(divisor).doubleValue())));
        return resDto;
    }

    @Override
    public BossBordResDto bossBord(BossBordReqDto reqDto) {

        if (StringUtils.isBlank(reqDto.getCompanyUuid())) {
            throw new TServerException("公司信息不能为空！");
        }
        if (StringUtils.isBlank(reqDto.getUserId())) {
            throw new TServerException("用户信息不能为空！");
        }
        if (StringUtils.isBlank(reqDto.getDimension())) {
            throw new TServerException("日期维度不能为空！");
        }
        if (StringUtils.isBlank(reqDto.getBeginTime())) {
            throw new TServerException("开始时间不能为空！");
        }
        if (StringUtils.isBlank(reqDto.getEndTime()) && reqDto.getDimension().equals(DimensionEnum.WEEK.getCode())) {
            throw new TServerException("结束时间不能为空");
        }

        DateStyle dateStyle = reqDto.getDimension().equals(DimensionEnum.MONTH.getCode()) ? DateStyle.YYYY_MM : DateStyle.YYYY_MM_DD;
        Date beginTime = DateUtils.StringToDate(reqDto.getBeginTime(), dateStyle);
        Date endTime = null;
        if (StringUtils.isNotBlank(reqDto.getEndTime())) {
            endTime = DateUtils.StringToDate(reqDto.getEndTime(), DateStyle.YYYY_MM_DD);
        }
        if(reqDto.getDimension().equals(DimensionEnum.DAY.getCode())){
        	endTime = DateUtils.addDay(beginTime, 1);
        } else {
        	endTime = DateUtils.addDay(endTime, 1);
        }

        DecimalFormat df = new DecimalFormat("#,###");
        BigDecimal divisor = new BigDecimal("10000");
        CustomerPremisesDto customerPremisesDto = new CustomerPremisesDto();
        customerPremisesDto.setCompanyId(reqDto.getHigherId());
        customerPremisesDto.setCreateTimeBefore(beginTime);
        customerPremisesDto.setCreateTimeAfter(endTime);
        customerPremisesDto.setDimension(reqDto.getDimension());
        
        // 添加权限相关数据作为查询条件
        List<Long> premisesIds = premisesPermissionService.getPartnerPremisesPermission(Long.parseLong(reqDto.getUserId()));
        if(CollectionUtils.isEmpty(premisesIds)){
        	customerPremisesDto.setAuthorityPremisesIds(Arrays.asList(-1L));
        }else{
        	customerPremisesDto.setAuthorityPremisesIds(premisesIds);
        }
        // 机构权限.直接以机构来查询.
        List<Long> deptPermissionList = deptPermissionService.getPartnerDeptPermission(Long.parseLong(reqDto.getUserId()));
        customerPremisesDto.setAgencyDeptIds(deptPermissionList);
        // 置业顾问数据
        List<EstateAdviser> estateAdviserList = estateAdviserService.selectListByPartner(Long.parseLong(reqDto.getUserId()));
        if (CollectionUtils.isNotEmpty(estateAdviserList)) {
            List<String> adviserUuids = estateAdviserList.stream().map(EstateAdviser::getAdviserUuid).collect(Collectors.toList());
            customerPremisesDto.setAdviserUuids(adviserUuids);
        }
        
        //有效报备数统计
        Future<String> validReportCountFuture = customerPremisesService.queryValidReportCount(customerPremisesDto);
        //有效到访数统计
        Future<String> validVisitCountFuture =  customerPremisesService.queryValidVisitCount(customerPremisesDto);
        // 认筹数
        Future<String> payDepositCountFuture = customerPremisesService.queryPayDepositCountCount(customerPremisesDto);
        // 认购数
        Future<String> subscribeTotalFuture = customerPremisesService.querySubscribeTotalCount(customerPremisesDto);
        //签约数统计
        Future<String> signCountFuture = customerPremisesService.querySignCount(customerPremisesDto);
        //签约业绩统计
        Future<String> signAmountCountFuture = customerPremisesService.querySignAmountCount(customerPremisesDto);

        BossBordResDto resDto = new BossBordResDto();
        
        try {
        	resDto.setValidReportCount(validReportCountFuture.get());
            resDto.setValidVisitCount(validVisitCountFuture.get());
			resDto.setPayDepositCount(payDepositCountFuture.get());
			resDto.setSubscribeTotal(subscribeTotalFuture.get());
	        resDto.setSignCount(signCountFuture.get());
	        String signAmountCountString = signAmountCountFuture.get();
	        BigDecimal signAmountCount = new BigDecimal(0); 
	        if(StringUtils.isNotEmpty(signAmountCountString) && !"null".equals(signAmountCountString)) {
	        	signAmountCount = new BigDecimal(signAmountCountString);
	        	resDto.setSignAmountCount(df.format(Math.round(signAmountCount.divide(divisor).doubleValue())));
	        }else {
	        	resDto.setSignAmountCount("0");
	        }
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
       
        return resDto;
    }

    @Override
    public GetDevPremisesExportResDto getDevPremises(GetDevPremisesExportReqDto reqDto) {
        GetDevPremisesExportResDto resDto = new GetDevPremisesExportResDto();
        CustomerPremisesDto customerPremisesDto = new CustomerPremisesDto();
        if (reqDto.getRecommenderIds() != null && reqDto.getRecommenderIds().size() > 0) {
            customerPremisesDto.setRecommenderIds(reqDto.getRecommenderIds());
        }
        if (CollectionUtils.isNotEmpty(reqDto.getPremisesIds())) {
            customerPremisesDto.setPremisesIds(reqDto.getPremisesIds());
        }else{
            // 渠道经理所属经纪人
            List<List<Long>> staffIds = getStaffIdsByPrincipal(Long.valueOf(reqDto.getUserId()));
            if(CollectionUtils.isNotEmpty(staffIds)) {
                customerPremisesDto.setPrincipalStaffIds(staffIds);
            }
        }
        customerPremisesDto.setValidateData(reqDto.isValidateData());
        customerPremisesDto.setStartDate(reqDto.getStartDate());
        customerPremisesDto.setEndDate(reqDto.getEndDate());
        customerPremisesDto.setDevCompanyId(reqDto.getDevCompanyId());
        List<Long> agencyDeptIds = deptPermissionService.getPartnerDeptPermission(Long.valueOf(reqDto.getUserId()));
        customerPremisesDto.setAgencyDeptIds(agencyDeptIds);
        Integer pageSize = reqDto.getPageSize();
        Integer pageNum = reqDto.getPageNum();

        //推荐人维度
        if ("0".equals(reqDto.getStatus())) {
            int total = customerPremisesMapper.getDevPremisesCountByRec(customerPremisesDto);
            List<DevPremisesExport> devPremisesInfoByRec = customerPremisesMapper.getDevPremisesInfoByRec(customerPremisesDto, (pageNum - 1) * pageSize, pageSize);
            Page<DevPremisesExport> page = new Page<>(total, devPremisesInfoByRec);
            page.setPageNumber(pageNum);
            page.setPageSize(pageSize);
            resDto.setDevPremisesExportPage(page);
        } else {
            //楼盘维度
            int total = customerPremisesMapper.getDevPremisesCountByPre(customerPremisesDto);
            List<DevPremisesExport> devPremisesInfoByPre = customerPremisesMapper.getDevPremisesInfoByPre(customerPremisesDto, (pageNum - 1) * pageSize, pageSize);
            Page<DevPremisesExport> page = new Page<>(total, devPremisesInfoByPre);
            page.setPageNumber(pageNum);
            page.setPageSize(pageSize);
            resDto.setDevPremisesExportPage(page);
        }
        return resDto;
    }

    @Override
    public List<DevPremisesExport> exportDevPremises(GetDevPremisesExportReqDto reqDto) {
        CustomerPremisesDto customerPremisesDto = new CustomerPremisesDto();
        if (reqDto.getRecommenderIds() != null && reqDto.getRecommenderIds().size() > 0) {
            customerPremisesDto.setRecommenderIds(reqDto.getRecommenderIds());
        }
        if (CollectionUtils.isNotEmpty(reqDto.getPremisesIds())) {
            customerPremisesDto.setPremisesIds(reqDto.getPremisesIds());
        }else{
            // 渠道经理所属经纪人
            List<List<Long>> staffIds = getStaffIdsByPrincipal(Long.valueOf(reqDto.getUserId()));
            if(CollectionUtils.isNotEmpty(staffIds)) {
                customerPremisesDto.setPrincipalStaffIds(staffIds);
            }
        }
        customerPremisesDto.setValidateData(reqDto.isValidateData());
        customerPremisesDto.setStartDate(reqDto.getStartDate());
        customerPremisesDto.setEndDate(reqDto.getEndDate());
        customerPremisesDto.setDevCompanyId(reqDto.getDevCompanyId());

        List<Long> agencyDeptIds = deptPermissionService.getPartnerDeptPermission(Long.valueOf(reqDto.getUserId()));
        customerPremisesDto.setAgencyDeptIds(agencyDeptIds);

        //推荐人维度
        if ("0".equals(reqDto.getStatus())) {
            return customerPremisesMapper.getDevPremisesExportByRec(customerPremisesDto);
        } else {
            //楼盘维度
            return customerPremisesMapper.getDevPremisesExportByPre(customerPremisesDto);
        }
    }

    @Override
    public GetVisitStateResDto getVisitStateList(GetVisitStateReqDto params) throws Exception {
        CustomerPremisesDto entity = new CustomerPremisesDto();
        GetVisitStateResDto resDto = new GetVisitStateResDto();
        List<Long> premisesIds = params.getPremisesIds();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<VisitStateInfo> list = new ArrayList<>(4);
        list.add(new VisitStateInfo("首次到访",0L,0L,"0.00%","0"));
        list.add(new VisitStateInfo("2次到访",0L,0L,"0.00%","0"));
        list.add(new VisitStateInfo("3次到访",0L,0L,"0.00%","0"));
        list.add(new VisitStateInfo("3次以上到访",0L,0L,"0.00%","0"));
        if (premisesIds != null && premisesIds.size() > 0) {
            entity.setPremisesIds(premisesIds);
        }

        if (StringUtils.isNotEmpty(params.getStartDate())) {
            String sDate = params.getStartDate() + " 00:00:00";
            entity.setStartDate(sDate);
        }

        if (StringUtils.isNotEmpty(params.getEndDate())) {
            String eDate = params.getEndDate() + " 23:59:59";
            entity.setEndDate(eDate);
        }

        if (params.getDevCompanyId() == 0) {
            throw new Exception("渠道公司id不能为空!");
        }

        entity.setDevCompanyId(params.getDevCompanyId());
        List<Long> agencyDeptIds = deptPermissionService.getPartnerDeptPermission(Long.valueOf(params.getUserId()));
        entity.setAgencyDeptIds(agencyDeptIds);
        List<VisitStateInfo> visitStateList = customerPremisesMapper.getVisitStateList(entity);
        list.removeAll(visitStateList);
        for (VisitStateInfo checkItem : list) {
            switch (checkItem.getVisitType()) {
                case "首次到访":
                    visitStateList.add(0, checkItem);
                    break;
                case "2次到访":
                    visitStateList.add(1, checkItem);
                    break;
                case "3次到访":
                    visitStateList.add(2, checkItem);
                    break;
                case "3次以上到访":
                    visitStateList.add(3, checkItem);
                    break;
            }
        }
        resDto.setGetVisitStateList(visitStateList);
        if (StringUtils.isNotEmpty(params.getStartDate())) {
            resDto.setStartDate(params.getStartDate());
        }
        if (StringUtils.isEmpty(params.getEndDate())) {
            resDto.setEndDate(dateFormat.format(new Date()));
        } else {
            resDto.setEndDate(params.getEndDate());
        }
        return resDto;
    }

    /**
     * 获取渠道经理能查看的经纪人报备
     * @param userId
     * @return
     */
    @Override
    public List<List<Long>> getStaffIdsByPrincipal(Long userId) {
        List<List<Long>> staffIds = new ArrayList<>();
        DepartmentDto departmentDto = new DepartmentDto();
        departmentDto.setPrincipal(userId);
        List<Department> departmentList = departmentDao.selectListByDto(departmentDto);
        if(CollectionUtils.isNotEmpty(departmentList)){
            List<Long> companyIds = departmentList.stream().map(Department::getMerchantId).collect(Collectors.toList());
            PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
            partnerInfoDto.setCompanyIds(companyIds);
            List<PartnerInfo> partnerInfoList = partnerInfoService.selectListByDto(partnerInfoDto);
            int maxSize = 500;
            if (CollectionUtils.isNotEmpty(partnerInfoList)) {
                int page = partnerInfoList.size() / maxSize;
                int iCount = partnerInfoList.size() % maxSize;
                for(int ii=0; ii<=page; ii++){
                    List<Long> staffIdList = new ArrayList<>();
                    if(ii == page){
                        for(int jj = ii*maxSize; jj<ii*maxSize+iCount; jj++ ){
                            staffIdList.add(partnerInfoList.get(jj).getId());
                        }
                    }else{
                        for(int jj =ii*maxSize; jj<(ii+1)*maxSize; jj++ ){
                            staffIdList.add(partnerInfoList.get(jj).getId());
                        }
                    }
                    if(staffIdList.size()>0){
                        staffIds.add(staffIdList);
                    }
                }
            }
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(1009/1000);
        System.out.println(1009%1000);
    }
}
